import 'dotenv/config';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { LoggerService } from './common/logger/logger.service';
import { TransformInterceptor } from './common/interceptor/transform';
import { HttpExceptionFilter } from './common/filter/httpException.filter';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import insertPermissions from './common/utils/insertPermissions';
import { NestExpressApplication } from '@nestjs/platform-express';
import { join } from 'path';
import { MainExceptionFilter } from './common/filter/MainException.filter';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);

  // 注册全局 logger 拦截器
  const loggerService = app.get(LoggerService);
  app.useGlobalInterceptors(new TransformInterceptor(loggerService));
  // 注册全局错误的过滤器
  // app.useGlobalFilters(new MainExceptionFilter());
  app.useGlobalFilters(new HttpExceptionFilter(loggerService));


  // 视图
  app.useStaticAssets(join(__dirname, '..', 'public'));
  app.setBaseViewsDir(join(__dirname, '..', 'views'));
  app.setViewEngine('hbs');

  // 设置swagger文档
  const config = new DocumentBuilder()
    .setTitle('管理后台')
    .setDescription('管理后台接口文档')
    .setVersion('1.0')
    .addBearerAuth()
    .build();

  const document = SwaggerModule.createDocument(app, config);

  // 首次启动时，将权限插入数据库
  // await insertPermissions(document);

  SwaggerModule.setup('docs', app, document);
  // 启用CORS
  app.enableCors();

  await app.listen(process.env.PORT ?? 3000);
}

bootstrap();
